package com.winexpress.order;

import com.winexpress.product.ProductManagementWS;
import com.winexpress.product.ProductManagementWS_Service;
import com.winexpress.util.SessionAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;
import java.io.IOException;
import java.text.DecimalFormat;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

@WebServlet(name = "Cart", urlPatterns = {"/cart/*"})
public class Cart extends HttpServlet {

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/ProductManagementWS.wsdl")
    private ProductManagementWS_Service service;

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/OrderManagementWS.wsdl")
    private OrderManagementWS_Service service_1;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        ProductManagementWS port0 = service.getProductManagementWSPort();
        OrderManagementWS port1 = service_1.getOrderManagementWSPort();

        //If Checkout Action
        String checkOut = request.getParameter("checkout");
        if (checkOut != null) {
            String items = (String) session.getAttribute("items");
            String user = (String) session.getAttribute(SessionAttributes.USER_ID);
            Double sum = new Double(request.getParameter("paymentSum")).doubleValue();

            if (user == null) {
                request.setAttribute("alert1", "1");
                response.sendRedirect("/WineXpressClient/loginFail.jsp");
            } else if (sum-0 > 0.0000001) {
                Long wid = Long.parseLong(user);
                OrderMessage outMessage = new OrderMessage();
                outMessage.setUserID(wid);
                outMessage.setItems(items);
                OrderHistory oh = port1.createOrder(outMessage);
                DecimalFormat df = new DecimalFormat("#.##");
                session.setAttribute("paymentAmount", df.format(sum));
                session.setAttribute("orderHistroy", oh);
            }else{
               response.sendRedirect("/WineXpressClient/searchManagement/shop"); 
            }
        }

        //If Update Action
        String editAction = request.getParameter("editAction");
        if (editAction != null) {
            String items = (String) session.getAttribute("items");
            List<String> array = new LinkedList<String>(Arrays.asList(items.split("\\;")));

            int index = array.indexOf((String) request.getParameter("editid"));
            array.set(index + 1, (String) request.getParameter("newamount"));

            items = "";
            for (String s : array) {
                items = items + s + ";";
            }
            session.setAttribute("items", items);
        }

        //If Delete Action
        String deleteAction = request.getParameter("deleteAction");
        if (deleteAction != null) {
            String items = (String) session.getAttribute("items");
            List<String> array = new LinkedList<String>(Arrays.asList(items.split("\\;")));

            int index = array.indexOf((String) request.getParameter("deleteid"));
            array.remove(index);
            array.remove(index);

            items = "";
            for (String s : array) {
                items = items + s + ";";
            }
            session.setAttribute("items", items);
        }

        //Get Number of Items in Cart
        int count = 0;
        if (session.getAttribute("items") == null) {
            int i = 0;
            request.setAttribute("itemsnum", i);
        } else {
            String items = (String) session.getAttribute("items");
            String[] array = items.split("\\;");
            for (int i = 1; i < array.length; i = i + 2) {
                count = count + Integer.parseInt(array[i]);
            }
            request.setAttribute("itemsnum", count);
        }
        //End Number of Items in Cart

        String items = (String) session.getAttribute("items");
        //Get Cart Itemslist
        if (items != null && items.length() != 0) {
            List<com.winexpress.product.Wine> wineList = null;
            if (port0.returnCartItems((String) session.getAttribute("items")) != null) {
                wineList = port0.returnCartItems((String) session.getAttribute("items"));
            }
            request.setAttribute("wineList", wineList);

            //String items = (String) session.getAttribute("items");
            String[] array = items.split("\\;");

            List<Integer> quantity = new ArrayList<Integer>();

            for (int i = 1; i < array.length; i = i + 2) {
                quantity.add(Integer.parseInt(array[i]));
            }
            request.setAttribute("quantity", quantity);
        }

        RequestDispatcher dispatcher;
        ServletContext servletContext = getServletContext();
        String page = request.getPathInfo();
        page = page.substring(1);
        dispatcher = servletContext.getNamedDispatcher(page);
        if (dispatcher == null) {
            dispatcher = servletContext.getNamedDispatcher("Error");
        }

        if (!response.isCommitted()) {
            dispatcher.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private java.util.List<com.winexpress.product.Wine> returnCartItems(java.lang.String arg0) {
        // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
        // If the calling of port operations may lead to race condition some synchronization is required.
        com.winexpress.product.ProductManagementWS port = service.getProductManagementWSPort();
        return port.returnCartItems(arg0);
    }

    private OrderHistory createOrder(com.winexpress.order.OrderMessage arg0) {
        // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
        // If the calling of port operations may lead to race condition some synchronization is required.
        com.winexpress.order.OrderManagementWS port = service_1.getOrderManagementWSPort();
        return port.createOrder(arg0);
    }
}
